//备注 进入参数
//avtivityid 活动id //activitytype(舍弃) 1限时抢购 2团购
//id 产品id
var actbill = require('../../../xc/model/pro_contents')
var html2wxml = require('../../../html2wxml/html2wxml.js');
var actcart = require('../../../xc/sys/cart')
var actgroupbill = require('../../shop/model/order_group')
var orderactbill = require('../../shop/model/order_bill')
var actwxlivebill = require('../../../xc/model/wxlive')

var app = getApp();

Page({
  mixins: [require('../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    wxlive: null,
    configdistributon: {},
    intervalid: -1,
    ishare: true,
    navopacity: 0,
    commentshow: 3,
    navlist: [],
    xcmodel: {

    },
    actstatus: -1,
    owngroupstatus: "-1",
    grouplistshow: false,
    cartlistnum: 0,
    viprank: null,
    taskid: -1,
    basicurl: app.globalData.basicurl
  },
  onClosegroup() {
    this.setData({
      grouplistshow: false
    });
  },
  onShowgroup() {
    this.setData({
      grouplistshow: true
    });
  },
  showevalists() {
    this.selectComponent("#evalists").init(this.data.xcmodel.id)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


  },

  confgset(config) {
    //主题设置
    var updateconfig = {};
    if (config.vip) {
      if (config.vip.status == 1) {
        var update = {}
        var rank = config.vip.rank;
        updateconfig['viprank'] = rank
        console.log("rank")
        console.log(rank)
      }
    }

    if (config.task) {
      updateconfig['taskname'] = config.task.taskname
      updateconfig['iconimg'] = config.task.icon

    }
    console.log("config")

    console.log(config)

    if (config.distribution) {
      console.log(config.distribution)
      updateconfig['configdistributon'] = config.distribution
    }
    if(config.payment){
      updateconfig['paymentconfig'] = config.payment;
      
    }
    var unit="￥"
    if(config.yihuo){
      if(config.yihuo.status==1){
        unit=config.payment.balancepayunit
      }
      updateconfig['yihuoconfig'] = config.yihuo
      updateconfig['unit'] = unit

    }
    if (config.order) {
      var owngroupstatus = config.order.owngroupstatus
      updateconfig['orderconfig'] = config.order

      updateconfig['owngroupstatus'] = owngroupstatus
      if (config.order.cart) {
        updateconfig['cartstatus'] = config.order.cart;
      } else {
        updateconfig['cartstatus'] = 1
      }
    }
    if (config.prothem && config.prothem.themcolor) {
      var themconfig = config.prothem.themcolor.config;
      updateconfig['themconfig'] = themconfig
    }
    if (config.rebate) {
      updateconfig['configrebate'] = config.rebate
    }
    if (config.prothem && config.prothem.detail) {
      var detailconfig = config.prothem.detail.proconfig;
      var customStyle = config.prothem.detail.customStyle;
      var popconfig = config.prothem.popup.proconfig;
      var popCustomStyle = config.prothem.popup.customStyle;
      updateconfig['detailconfig'] = detailconfig
      updateconfig['customStyle'] = customStyle
      updateconfig['popconfig'] = popconfig
      updateconfig['popCustomStyle'] = popCustomStyle
    }
    console.log("updateconfig")

    console.log(updateconfig)
    this.setData(updateconfig)
    //导航设置
    var commentshow = this.data.commentshow
    if (config.proconfig) {
      commentshow = config.proconfig.pro.commentshow
    }
    var detailconfig = config.prothem.detail.proconfig;
    if (detailconfig.evaluate.status == 1 || detailconfig.moreinfor.status == 1) {
      var navlist = [{
        id: "main",
        name: "商品"
      }]
      if (commentshow != "3" && detailconfig.evaluate.status == 1) {
        navlist.push({
          id: "evaluate",
          name: "评价"
        })
      }
      if (detailconfig.moreinfor.status == 1) {
        navlist.push({
          id: "infor",
          name: "详情"
        })
      }
      // navlist.push({id: "recommend",name: "推荐" })
      this.setData({
        commentshow,
        navlist
      })
    }

  },
  gettaskinfo(taskid) {
    var that = this;
    orderactbill.gettaskinfo(taskid).then(res => {
      if (res.status == 1) {
        console.log("gettaskinfo")
        console.log(res.obj)
        that.setData({
          taskinfo: res.obj
        })
      }
    })
  },
  xcloaddata: function (options, config) {
    var that = this;

    var activityid = 0
    if (options.activityid) {
      activityid = options.activityid
    }
    this.getmodel(options.id, activityid)

    wx.getSystemInfo({
      success: function (res) {
        console.log("systemInfo")

        console.log(res)
        that.setData({
          systemInfo: res
        });
      }
    })
    if (options.taskid) {
      app.globalData.share.taskid = options.taskid
      this.setData({
        taskid: options.taskid
      })
      this.gettaskinfo(options.taskid)
    }
    
    //开启直播
    if (config.wxlive && config.wxlive.status == 1) {
      this.wxliveconfig(options)
    }

    if (options['orderid']) {
      this.getorderinfo(options['orderid'])
      this.setData({
        orderid: options['orderid']
      })
    }
    //扫码进入获取参数
    // if (options.scene) {
    //   var scene = decodeURIComponent(options.scene);
    //   var scenedata = scene.split("_");
    //   options.shareid = scenedata[0];
    //   options.id = scenedata[1];
    //   options.activityid = scenedata[2];
    // }

    //获取图片基础路径
    this.setbasicurl()

    this.confgset(config)

    var that = this;
    // var activityid = 0
    // if (options.activityid) {
    //   activityid = this.data.options.activityid
    // }
    // this.setData({
    //   id:options.id,
    //   activityid:activityid
    // })

    var Comcouponpro = that.selectComponent("#couponpro")
    Comcouponpro.getdata(options.id)

    this.loadcardlength()

    // console.log("options")
    // console.log(options)
  },
  //获取设置全局key
  getkey() {
    var that = this;
    actwxlivebill.getkey().then(function (res) {
      if (res["status"] == 1) {
        console.log(res.obj)
      } else {
        that.error(res["message"])
      }
    })
  },
  wxliveconfig(options) {
    this.getkey()
    var url = 'xc_lshop/shop/pro/proinfo?id=' + options.id; // 小程序商详页路径
    if (options.activityid) {
      url = url + '&activityid=' + options.activityid
    } else {
      url = url + '&activityid=0'
    }
    var goodsKey = ['id', 'activityid']; // 商品key列表（支持多个key），需要在添加商品时用我们提供的api接口【详见第4节 挂件api接口】传入商品key列表（如示例的'pid', 'sid'）
    var type = 0; // 0. 显示直播、预告、商品讲解、回放其中之一的挂件；1. 只显示直播的挂件；2. 只显示预告的挂件；3. 只显示商品讲解的挂件；4. 只显示回放的挂件
    var customParams = encodeURIComponent(JSON.stringify({
      path: 'xc_lshop/shop/pro/proinfo',
      id: options.id
    })); // 开发者在直播间页面路径上携带自定义参数（如示例中的path和pid参数），后续可以在分享卡片链接和跳转至商详页时获取，详见【获取自定义参数】、【直播间到商详页面携带参数】章节（上限600个字符，超过部分会被截断）
    var closePictureInPictureMode = 0; // 是否关闭小窗
    var wxlive = {
      url,
      goodsKey,
      type,
      customParams,
      closePictureInPictureMode
    }
    this.setData({
      wxlive
    })
  },
  //获取订单信息
  getorderinfo(orderid) {
    var that = this;
    orderactbill.getmodel(orderid).then(res => {
      if (res.status == 1) {
        console.log("res.obj")
        console.log(res.obj)
        that.setData({
          orderinfo: res.obj
        })
        // this.createqrcode(res.obj['status'],res.obj['ordernum']) 
        // that.selectComponent("#orderinfortop").set(res.obj)
        // that.selectComponent("#orderinforbottom").set(res.obj)
      }
    })
  },
  // 注册
  login() {
    var app = getApp()
    var that = this
    app.xc_sys_config.authop.oppower("login").then(function (res) {
      that.setData({
        "memberinfo": app.globalData.member.memberinfo
      })
    })
  },

  afterlogin: function (options, config, userinfo) {
    if (userinfo.memberinfo) {
      this.setData({
        memberinfo: userinfo.memberinfo
      })

    }


  },
  getmodel(id, activityid) {
    var that = this
    actbill.getmodel(id, activityid).then(res => {
      if (res.status == 1) {
        console.log("getmodel")
        console.log(res)

        html2wxml.html2wxml('article', res.obj.contents, this, 5);
        var xcmodelobj = res.obj;
        var acttype = 0; //活动类型
        if (activityid && xcmodelobj['activitybrief']) {
          if ((xcmodelobj['activitybrief']['grade'] != -1) && that.data.memberinfo) {
            if ((!that.data.memberinfo.vipinfo) || (that.data.memberinfo.vipinfo['index'] != xcmodelobj['activitybrief']['grade'])) {
              wx.redirectTo({
                url: '/xc_lshop/shop/pro/proinfo?id=' + id,
              })
            }
          }
          acttype = xcmodelobj['activitybrief']['itype']
          var actinforstock = ""
          if (xcmodelobj.skudata && xcmodelobj.skudata.stockdata) {
            actinforstock = xcmodelobj.skudata.stockdata;
          }
          // var actinforstock = xcmodelobj.skudata.stockdata;
          if (xcmodelobj.guigetype == 1 && actinforstock) {
            // var min = xcmodelobj.realprice;
            var min = actinforstock[0].activityprice;

            var sales = 0;
            actinforstock.forEach(element => {
              if (element['activityprice']) {
                if (parseInt(min) > parseInt(element['activityprice'])) {
                  min = element['activityprice'];
                }
              }
              if (element.basicesales) {
                sales += parseInt(element.basicesales);
              }
            });
            xcmodelobj['activitybrief']['sales'] = sales;
            xcmodelobj['activitybrief']['minprice'] = min;
          }
          if (xcmodelobj.activitybrief.starttime) {
            var thetime = xcmodelobj.activitybrief.starttime;
            var theendtime = xcmodelobj.activitybrief.endtime;
            var stime = new Date(Date.parse(thetime.replace(/-/g, "/")));
            var etime = new Date(Date.parse(theendtime.replace(/-/g, "/")));
            var curDate = new Date();
            var actstatus = 0;


            if (etime < curDate) {
              actstatus = 2 //活动结束 3上限 限购
            } else if (curDate < stime) { //活动未开始
              actstatus = -1;
            } else { //活动进行
              actstatus = 1
              that.autoexcel();
            }
            that.setData({
              actstatus: actstatus,
            })
          }
        }

        if (acttype == 2) {
          that.getgrouplist(id, activityid);
        }
        if (xcmodelobj['customdata'] && xcmodelobj['customdata']['poster']['status'] == -1) {
          var posterstatus = false
        } else {
          var posterstatus = true
        }
        console.log("xcmodelobj")

        console.log(xcmodelobj)
        that.setData({
          id: id,
          activityid: activityid,
          activitytype: acttype,
          xcmodel: xcmodelobj,
          posterstatus: posterstatus
        })
        console.log("xcmodelobj")
        console.log("xcmodelobj")

        console.log(posterstatus)
        wx.setNavigationBarTitle({
          title: res.obj.name
        });
      }
    })
  },
  tocart() {
    wx.navigateTo({
      url: '/xc_lshop/shop/cart/index',
    })
  },
  loadcardlength() {
    var that = this

    actcart.loadcartlocal().then(res => {
      if (res.totalnuminfo) {
        that.setData({
          cartlistnum: res.totalnuminfo.totalnum
        })
      }
    })

  },
  getgrouplist(id, activityid) {
    var that = this
    var strwhere = {};
    strwhere['aid'] = activityid;
    strwhere['id'] = id;
    actgroupbill.getgrouplist(strwhere).then(res => {

      that.setData({
        groupamount: res['groupamount'],
        grouplist: res['grouplist'],
        swiperlist: res['swiperlist'],
        usergroup: res['usergroup']
      })
    })

  },
  //倒计时结束
  ontimeFinish(e) {
    var that = this;
    that.getgrouplist(that.data.id, that.data.activityid)
  },
  //监听倒计时
  ontimeChange(e) {
    console.log(e)
    var that = this;
    // var failconfig=1;
    var lasttime = 0;
    if (that.data.orderconfig) {
      var orderconfig = that.data.orderconfig;
      // console.log(orderconfig)
      if (orderconfig.groupfailop == 4) {
        lasttime = orderconfig.lastmin * 60;
      }
      // failconfig=orderconfig.groupfailop;
    }
    if (e.detail == lasttime) {
      that.getgrouplist(that.data.id, that.data.activityid)
      // var model={};
      // model['groupid']=usergroup.id;
      // actgroupbill.changegroup(model).then(function (restmodel) {

      // })

    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //分享
  proshare() {
    console.log("分享")
    this.selectComponent("#proshare").showSharefunc();

  },
  //邀请好友
  invite() {
    this.selectComponent("#widgetsshare").showSharefunc();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    this.loadcardlength();
    if (this.data.actstatus == 1) {
      this.autoexcel()
    }
    if (that.data.id && that.data.activityid && that.data.activitytype == 2) {
      that.getgrouplist(that.data.id, that.data.activityid)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.clearauto();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.clearauto();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //优先顺序 全局配置<默认(商品名 + 商品图 )<自定义分享
  onShareAppMessage: function () {
    var app = getApp()
    var xcmodel = this.data.xcmodel;
    var sharetitle = "";
    var shareimg = "";

    if (xcmodel['customdata'] && xcmodel['customdata']['share'] && xcmodel['customdata']['share']['status'] == 1) {
      sharetitle = xcmodel['customdata']['share']['name'];
      shareimg = xcmodel['customdata']['share']['imageUrl']
    } else {
      if (xcmodel.name) {
        sharetitle = xcmodel.name
      } else {
        sharetitle = this.shasretitle()
      }
      if (xcmodel.simg) {
        shareimg = xcmodel.simg
      } else {
        shareimg = this.data.shareimg
      }
    }

    // console.log("ddddddddd")
    // console.log(sharetitle)

    const sharepath = app.xc_sys_config.getshareurl()

    return {
      title: sharetitle,
      path: sharepath,
      imageUrl: shareimg
    }
  },
  onShareTimeline() {
    var app = getApp()
    // var sharetitle = this.shasretitle()
    const sharepara = app.xc_sys_config.getshareurl("para")

    var xcmodel = this.data.xcmodel;
    var sharetitle = "";
    var shareimg = "";

    if (xcmodel['customdata'] && xcmodel['customdata']['share'] && xcmodel['customdata']['share']['status'] == 1) {
      sharetitle = xcmodel['customdata']['share']['name'];
      shareimg = xcmodel['customdata']['share']['imageUrl']
    } else {
      if (xcmodel.name) {
        sharetitle = xcmodel.name
      } else {
        sharetitle = this.shasretitle()
      }
      if (xcmodel.simg) {
        shareimg = xcmodel.simg
      } else {
        shareimg = this.data.shareimg
      }
    }


    return {
      title: sharetitle,
      query: sharepara,
      imageUrl: shareimg

    }
  },
  joinbuy(ev) {
    var dataset = ev.currentTarget.dataset
    var item=dataset.item
    if (!this.data.memberinfo) {
      this.login();
    }
    //活动未开始/结束不能购买 达到上限
    if (this.data.activityid != 0 && (this.data.actstatus == -1 || this.data.actstatus == 2 || this.data.xcmodel.limitinfo.limitnum == 0)) {
      return;
    }

    var that = this
    var option = "";
    if (this.data.activityid && this.data.activitytype) {
      option = {
        aid: this.data.activityid,
        atype: this.data.activitytype
      }
    }
    if (item.pronum) {

      option['fixednum'] = item.pronum
    }

    if (item.id) {
      option['groupid'] = item.id
      app.globalData.share.taskid= item.id
    }
  
    actbill.showattrchose(that, that.data.id, that.data.selected, ev.currentTarget.dataset.op, option)

  },
  buyop: function (ev) {
    var dataset = ev.currentTarget.dataset
    if (!this.data.memberinfo) {
      this.login();
    }

    //活动未开始/结束不能购买 达到上限
    if (this.data.activityid != 0 && (this.data.actstatus == -1 || this.data.actstatus == 2 || this.data.xcmodel.limitinfo.limitnum == 0)) {
      return;
    }
    //后台设置能否自己拼团
    if (dataset.pid && dataset.pid != 1) { //团购部分
      if (this.data.owngroupstatus != 1) {
        var leaderid = ev.currentTarget.dataset.leaderid;
        if (this.data.memberinfo.id == leaderid) {
          wx.showToast({
            icon: "error",
            title: '您已是团长',
          })
          return;
        }
      }
      //团长不可在发起拼团
      if (!ev.currentTarget.dataset.groupid && this.data.usergroup && this.data.usergroup.leaderid == this.data.memberinfo.id) {

        return;
      }
    }


    var that = this
    var option = "";
    if (this.data.activityid && this.data.activitytype) {
      option = {
        aid: this.data.activityid,
        atype: this.data.activitytype
      }
    }
    if (ev.currentTarget.dataset.pid) {
      var pid = ev.currentTarget.dataset.pid;
      if (pid == 1) {
        option = {
          aid: 0,
          atype: 0
        }
      }
    }
    if (ev.currentTarget.dataset.groupid) {
      option['groupid'] = ev.currentTarget.dataset.groupid
    }
    if (ev.currentTarget.dataset.type == 'rebate') {
      option = {
        aid: -1001,
        atype: -1001
      }
    }

    // var fixednum=0;
    if (this.data.taskid && this.data.taskinfo) {
      option['fixednum'] = this.data.taskinfo.pronum
    }



    actbill.showattrchose(that, that.data.id, that.data.selected, ev.currentTarget.dataset.op, option)
  },
  // 加购成功事件
  aftercart(e) {
    this.loadcardlength()
  },
  attrchoose: function (e) {
    var choosed = e.detail;
    if (choosed.proid == this.data.xcmodel.id) {
      var choosedinfor = "";
      if (e.detail.attrs) {
        for (var i in e.detail.attrs) {
          if (choosed.attrs[i].keyname != '') {
            choosedinfor += "【" + choosed.attrs[i].keyname.name + "】";
          }
        }
      }
      console.log("selected")

      console.log(e.detail)

      this.setData({
        selected: e.detail,
        choosedinfor: choosedinfor
      })

    }
  },

  navCurchange: function (e) {
    var that = this;
    var update = {};
    update['scrollnavCur'] = e.detail.index;
    this.setData(update)
  },
  // 滚动触发事件
  VerticalMain: function (e) {



    var that = this;
    let list = that.data.navlist;
    var scrollTop = e.detail.scrollTop


    var updata = {};
    if (scrollTop >= 0 && scrollTop < 200) {
      updata['navopacity'] = scrollTop / 2 * 0.01
    } else {
      if (this.data.navopacity != 1) {
        updata['navopacity'] = 1
      }
    }
    if (scrollTop > 400) {
      updata['backtopshow'] = true
    } else {
      updata['backtopshow'] = false
    }
    that.setData(updata)
    let view = wx.createSelectorQuery().selectAll(".scrollanchor");
    view.boundingClientRect(function (rects) {
      for (var a in rects) {
        if (rects[a].top > 0) {

          if (that.navCur != a) {

            that.setData({
              navCur: parseInt(a),
            })
          }
          break;
        }
      }

    }).exec()

  },

  couponpro: function () {
    var that = this;
    this.authop("coupon").then(rest => {
      if (rest["status"] != 1) {
        wx.showToast({
          title: rest["message"] ? rest["message"] : "获取信息失败",
        })
      } else {
        var userinfo = rest["userinfo"]
        var Comcouponpro = that.selectComponent("#couponpro")
        Comcouponpro.showinfo(userinfo, that.data.xcmodel.id)
      }
    })

  },
  //倒计时 清除
  clearauto: function (res) {
    var that = this;
    if (that.data.intervalid != -1) {
      clearInterval(that.data.intervalid)
      that.data.intervalid = -1;
      if (res == true) {
        that.setData({
          actstatus: 2
        })
      }

    }
  },
  //倒计时 开始
  autoexcel: function (rest) {
    // return;
    var that = this;
    if (!rest) {
      if (that.data.intervalid != -1) {
        return;
      }
    } else {
      that.clearauto();
    }
    that.data.intervalid = setInterval(function () {
      var theendtime = that.data.xcmodel.activitybrief.endtime;
      var e = new Date(Date.parse(theendtime.replace(/-/g, "/")));
      if (e <= new Date()) {
        that.clearauto(true);
      }
      that.setData({
        aunttime: new Date()
      })
    }, 1000)


  },
  backtop(e) {
    this.setData({
      scrollnavCur: parseInt(0),
    })
  }
})